﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace StockUtil
{
    public delegate void HotKeyHanlder();

    public static class HotKeyHelper
    {
        [DllImport("user32.dll")]
        static extern bool RegisterHotKey(IntPtr hWnd, int id, HotKeyModifiers modifiers, Keys key);

        [DllImport("user32.dll")]
        static extern bool UnregisterHotKey(IntPtr hWnd, int id);

        private static int keyid = 100;
        private static Dictionary<int, HotKeyHanlder> keymap = new Dictionary<int, HotKeyHanlder>();

        public static void Register(IntPtr hWnd, HotKeyModifiers modifiers, Keys key, HotKeyHanlder callBack)
        {
            if (!RegisterHotKey(hWnd, ++keyid, modifiers, key))
                throw new Exception("regist hotkey fail.");
            keymap[keyid] = callBack;
        }

        public static void Unregister(IntPtr hWnd, HotKeyHanlder callBack)
        {
            foreach (KeyValuePair<int, HotKeyHanlder> kvp in keymap)
            {
                if (kvp.Value == callBack)
                    UnregisterHotKey(hWnd, kvp.Key);
            }
        }

        public static void ProcessHotKey(Message m)
        {
            int id = m.WParam.ToInt32();
            HotKeyHanlder callback;
            if (keymap.TryGetValue(id, out callback))
            {
                callback();
            }
        }
    }

    [Flags()]
    public enum HotKeyModifiers
    {
        None = 0,
        Alt = 1,
        Ctrl = 2,
        Shift = 4,
        WindowsKey = 8
    }
}
